package com.example.task;

import com.example.mapper.AppointmentMapper;
import com.example.pojo.Appointment;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Component
public class CheckAppointmentStatus {
    @Resource
    private AppointmentMapper appointmentMapper;
    /**
     * 定时任务，每30分钟执行一次，检查预约状态，如果预约时间小于当前时间，则更新状态为已完成
     */
    @Scheduled(cron = "0 0/30 * * * ? ")
    public void updateCompletedStatus() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime fiveMinutesAgo = now.minusMinutes(5);

        // 查询所有预约时间为五分钟前且状态为1的预约
        List<Appointment> appointments = appointmentMapper.selectAllByTimeAndStatus(
                fiveMinutesAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                1
        );

        for (Appointment appointment : appointments) {
            // 更新状态为2
            appointment.setStatus(2);

            // 更新数据库
            appointmentMapper.updateStatus(appointment);
            log.info("更新预约状态为已完成，预约ID：{}", appointment.getId());
        }
    }
}
